<template>
  <div ref="charts"></div>
</template>
<script>
import { debounce } from '@/utils'
const OPTHIONS = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '2%',
    right: '4%',
    bottom: '8%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: true,
    axisLabel: {
      interval: 0,
      rotate: 30
    },
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: []
}
export default {
  props: {
    options: {
      type: Object,
      default: null
    }
  },
  watch: {
    options: {
      deep: true,
      handler: function() {
        this.updateCharts()
      }
    }
  },
  mounted() {
    this.initCharts()
    this.__resizeHanlder = debounce(() => {
      if (this.charts) {
        this.charts.resize()
      }
    }, 100)
    document.addEventListener('resize_chart', this.__resizeHanlder)
  },
  destroyed() {
    this.charts.dispose()
    this.charts = null
    document.removeEventListener('resize_chart', this.__resizeHanlder)
  },
  methods: {
    initCharts() {
      this.charts = this.$echarts.init(this.$refs.charts)
      this.charts.setOption(OPTHIONS)
      this.charts.showLoading()
    },
    updateCharts() {
      OPTHIONS.xAxis.data = this.options.xAxisData
      const chartOptions = Object.assign({}, OPTHIONS, this.options);
      this.charts.setOption(chartOptions)
      this.charts.hideLoading()
    }
  }
}
</script>
